package com.naughtybabystudio.android.shaketheworld;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class DisplaySurfaceView extends SurfaceView implements SurfaceHolder.Callback {

	private SurfaceHolder mHolder;
	private DisplayThread mDisplayThread;
	private boolean mHasSurface;
	private DisplayContent mDisplay;
	  
	public DisplaySurfaceView(Context context, DisplayContent display) {
		super(context);
		mDisplay=display;
		init();
	}
	private void init() {  
		mHolder = getHolder();  
		mHolder.addCallback(this);  
		mHasSurface = false;  
	}
	
	class DisplayThread extends Thread {
		private boolean done;
		
		DisplayThread() {
			super();
			done=false;
		}
		
		@Override
		public void run() {
//			super.run();
			SurfaceHolder surfaceHolder = mHolder;

			while (!done) {
				Canvas canvas = surfaceHolder.lockCanvas();

				//draw something here
				mDisplay.Draw(canvas);

				surfaceHolder.unlockCanvasAndPost(canvas);
				
				try {
					sleep(50);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		public void requestExitAndWait() {
			done = true;
			try {
				join();
			} catch (InterruptedException ex) {
			}
		}

		public void onWindowResize(int w, int h) {
		}
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		mHasSurface = true;
		if (mDisplayThread != null)
			mDisplayThread.start();
	}
	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		mHasSurface = false;  
	    pause();
	}
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	    if (mDisplayThread != null)
	    	mDisplayThread.onWindowResize(width, height);
	}
	
	public void resume() {
		if (mDisplayThread == null) {
			mDisplayThread = new DisplayThread();
			if (mHasSurface == true)
				mDisplayThread.start();
		}
	}
	
	public void pause() {
		if (mDisplayThread != null) {
			mDisplayThread.requestExitAndWait();
			mDisplayThread = null;
		}
	}
}
